package com.huazai.juc.cec.thread.august.twentySeven;

import lombok.extern.slf4j.Slf4j;

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.WeekFields;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author Seon
 * @date 2022/8/27 17:44
 */
@Slf4j
public class ScheduleDisplay {
    /**
     * 如何让每周四的晚上18:00:00来定时执行任务？测试成功！！！
     */
    public static void main(String[] args) {
        ScheduledExecutorService scheduledPool = Executors.newScheduledThreadPool(1);
        // 获取当前的时间
        LocalDateTime now = LocalDateTime.now();
        // 获取周四的时间
        LocalDateTime targetTime = now.withHour(18).withMinute(25).withSecond(0).withNano(0).with(DayOfWeek.SATURDAY);

        // 如果当前时间大于本周周四了，那就需要跳一下了。
        if (now.isAfter(targetTime)) {
            targetTime = targetTime.plusWeeks(1);
        }

        System.out.println("now = " + now);
        System.out.println("targetTime = " + targetTime);

        long initialDelay, period;
        // 中间的差值时间
        initialDelay = Duration.between(now, targetTime).toMillis();
        // 一周的时间
//        period = 1000 * 60 * 60 * 24 * 7;
        period = 1000;

        // initialDelay代表当前时间和周四的时间差， period代表周期
        scheduledPool.scheduleAtFixedRate(() -> {
            log.info("running...");
        }, initialDelay, period, TimeUnit.MILLISECONDS);
    }
}
